package com.zzl.car.controller;

import com.zzl.car.entity.Manager;
import com.zzl.car.exception.ZdpException;
import com.zzl.car.service.ZzwManagerLoginService;
import com.zzl.car.util.ZdpJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@CrossOrigin
@RestController
public class ZzwManagerLoginController {
    @Autowired
    private ZzwManagerLoginService managerLoginService;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    /*
     * 账号密码登录
     * 登录成功 返回 tokenid
     * */
    @PostMapping("/managerLogin")
    public Map<String, String> login(@RequestBody Map map) {
        String account= map.get("account").toString();
        String password= map.get("password").toString();
        //验证，如果登录成功，返回token给前端
        Manager manager = managerLoginService.getManagerByLogin(account, password);
        if (manager != null) {
            //登录成功,解析得到token
            String tokenID = ZdpJwtUtil.generate(account);
            //存储用户信息
            redisTemplate.opsForValue().set(account, manager, 6, TimeUnit.HOURS);
            //返回token
            Map<String, String> r = new HashMap<String, String>();
            r.put("tokenID", tokenID);
            r.put("name",manager.getName());
            return r;
        } else {
            //登录失败，抛出错误
            throw new ZdpException(2901, "用户名或密码错误");
        }
    }
}
